var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var price = 0;
var hot = 0;
var app = getApp();

var screnn_w = 320;

var wxAuthFail = true;
var inviteuid = 0;
var uid = '0';
var linkcode = '';
var topicid = "";
var dataall;
var loadingMore = false;
var allGoodsData = {};
var page = 1;
var hasMore = true;
var messagetmp = '';

Page({
  data: {
    util: util,

    page: 1,
    limit: 20,
    uid: '',
    token:'',
    
    data: [],
    noData: false,
    imgDomain: app.globalData.imgDomain,
    goodTypeName:'',
    goodTypeId: 0,
    pinSign: 0,

    postuid:'',
    toporder: 1,
    hasMore: true,
    hasLoadding: false,
    priceorder: 0,
    hotorder: 0,
    hidecata: true,
    allcata: [],
    nowcata: [],
    content_item_w: 100,
    goodTypeView_w: 100,
    colorSet: '',


    goodsList:[],
    currcata:0,
    isIphone_x: false,
    catadata:[],
    guigeData: [],
    selectGuige: '',
    countValue: 1,
    gwc_count: 0,
    waithao: 0,

    gcataid:"",
    username:'',


    attribute:'',//商品属性集合
    showAttribute:false, //控制商品有属性事显示

    showPrefood:false,
    showMainfood: false,
    showDrink: false,
    showSubDrink: false,

    drinksArray: [],
    prefoodArray:[],
    mainfoodArray: [],

    //八戒--------
    showMoreAct: false,
    actArr: [{ type: '首单', title: util.orgid == 17784 ? '新用户入学优惠信息' :"首单优惠信息" },
      { type: '满减', title: '满减优惠信息' },
      { type: '特价', title: util.orgid == 17784 ?  '特价课程':"特价商品" },
      { type: '超值', title: util.orgid == 17784 ? '超值课程' : "超值商品"}],
    // actArr: [{ type: '首', title: '新用户下单立减17元' },
    //         { type: '减', title: '满23减5元 满43减10元 满70减18元' },
    //         { type: '特', title: '超值20元套餐' }],

    tabcatadata: [{ cid: 0, cname: util.orgid == 17784 ? "课程" :"商品"},
                  { cid: 1, cname: "评论" },
                  { cid: 2, cname: util.orgid == 17784 ? "关于":"商家"}],
    commentcatadata: [{ cid: 0, cname: "全部" ,counts:0},
                      { cid: 1, cname: "满意", counts: 0},
                      { cid: 2, cname: "不满意", counts: 0}],
    tabcurrcata: 0,
    commentcurrcata: 0,
    hide_commentview: true,
    ghsIndex: 0, 
    
    // ------------------

  },
  onLoad: function (options) {
    allGoodsData = {};
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
    });
    if (util.orgid == 12545||util.orgid==14939) {
      var titlename = tc == 1 ? '線上點餐' : '线上点餐';
    }
    if (util.orgid != 12545&&util.orgid!= 14939) {
      var titlename = options.username;
      that.setData({
        titlename: titlename
      })
    }
    if(util.orgid==21145){
      titlename = tc == 1 ? '家家烘焙' : '家家烘焙';
    }
    if(util.orgid==12809){
      titlename = tc == 1 ? '三江精品汇' : '三江精品汇';
    }
    if(util.orgid==21780){
      titlename = tc == 1 ? '平通街商行' : '平通街商行';
    }
    if (util.orgid == 21398) {
      titlename = tc == 1 ? 'Steaks28 尚品' : 'Steaks28 尚品';
    }
    wx.setNavigationBarTitle({
      title: titlename,
    }); 

    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });
    wx.getSystemInfo({
      success: function (res) {
    
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screnn_w : res.windowWidth,
          content_w: res.windowWidth - 78,
          goodTypeView_w: (res.windowWidth - 78) / 3
        });
        
      }
    })
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('goodslist/goodslist', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });
    //获取颜色配置
    app.getColorSetData(function (color) {
      var col = color.goods_col ? parseInt(color.goods_col) : 3;
      col = col > 0 ? col : 3;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 5) / col,
        goodTypeView_w: screnn_w / 3
      })
      that.resetNavColor();
    });

    this.setData({
      goodTypeId: options.cataid ? options.cataid : '',
      postuid: options.uid ? options.uid : '',
      pinSign: options.pin ? options.pin : 0
    });

    
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          userinfo: res,
          token: res.token
        });

        if (util.orgid == 17784) {
          // that.getCommentList()
        }
      }
    }, '');
    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      if (util.orgid == '12545') {
        that.setData({
          org_name: res.uname
        })

      }
    });
    if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484){
      that.getghs();
    }
    //获取绑定门店信息
    app.GetUserInfo(options.uid, function (res) {
      console.log("绑定门店信息：", res);
      that.setData({
        ghs: res,
        ghsinfo: res
      })
      var latitude = 0;
      var longitude = 0;
      if (that.data.userinfo){

        latitude = that.data.userinfo.lat;
        longitude = that.data.userinfo.lon;
      }
      var distanStr;
      if (latitude && longitude) {
        var distan = app.getDistance(latitude, longitude, res.lat, res.lon);
        if (distan > 1000) {
          distanStr = (distan / 1000).toFixed(2) + 'km';
        } else {
          distanStr = distan.toFixed(0) + 'm';
        }
        that.data.ghsinfo.distanse = distanStr;
        that.data.ghsinfo.timetohere = (10*distan / 1000).toFixed(0);
        that.setData({
          ghsinfo: that.data.ghsinfo
        })

      }

      if (util.orgid == 18681 || util.orgid == 17784 || util.orgid == 12809|| util.orgid == 21780) {

        that.getghs();
        that.loadghsCommentList(res.uid, 1);
        that.getGongGaoTopic();
      }
    });
    
    var inviteuid = options.inviteuid;
   


    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    this.setData({
      gwc_count: gwc_datas.length
    });
    that.calTotalPrice();


    console.log("options = ", options);

    util.api({
      data: {
        "tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function (responseData) {
        console.log("goodstype", responseData.data);
        var goodsType = responseData.data;

        var goodId = options.cataid ? options.cataid : '';

        if(util.orgid==21145){
          goodId = 686;
        }
        if(util.orgid == 21398) {
          goodId = 703;
        }
        if (util.orgid == 21484) {
          goodId = 727;
        }

        if (util.orgid == 12809 && !goodId) {
          goodId = 162;
        }
        
        if (util.orgid == 21780) {
          goodId = 740;
        }
        console.log("goodId", goodId);
        that.setData({
          gcataid: goodId,
        });
        if(goodId =="0"){
          if(!goodsType.msg){
            dataall = goodsType;
            console.log("catadata==6==",dataall);
            that.setData({
              catadata: dataall,
              allGoodsDataArray: dataall,
              selectCata: dataall[0],
              gcataid: dataall[0]['goods_id'],
              nowcata: dataall[0].child
            });

            if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484) {
              that.getAllGoodsData();

            }else{
              that.loadGoodsListData(1); 
            }
          } else {
            wx.hideLoading();
          }
        }else{
            var cata = [];
            if(!goodsType.msg){
              for (var i = 0; i < goodsType.length; i++) {
                var gid = goodsType[i].goods_id;
                console.log("===gid===!:"+gid);
                if(goodId == gid){
                  cata = goodsType[i].child == undefined ? goodsType : goodsType[i].child;
                  break;
                }

              } 
              console.log("===cata===!:"+cata);
              if(cata && cata.length >=1 ){
                dataall = cata;
              }else{
                dataall = goodsType;
              }
              console.log("catadata==7==",dataall);
              that.setData({
                catadata: dataall,
                allGoodsDataArray: dataall,
                selectCata: dataall[0],
                nowcata: dataall
              });
              if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484) {
                that.getAllGoodsData();

              } else {
                that.loadGoodsListData(1);
              }
            } else {
              wx.hideLoading();
            }
        }
        
      }
    });


    that.getWaithao();

    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    });
    if (util.orgid == 17784) {
      // that.getCommentList()  
      // 获取门店
    }
    if (util.orgid == 18681) {
      that.setData({
        showSendTime: true
      })  
      that.datetimePickerInit()
    }
    if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484){
      that.setData({
        currHour:new Date().getHours()
      })
    }

  },


  loadMore:function(){
    if (!loadingMore && hasMore){
      page ++;
      if (this.data.searchVal && this.data.searchVal.length > 0) {
        this.search();
      } else {
        if (util.orgid != 21145 && util.orgid != 21398 
) {
          this.loadGoodsListData(page);

        }
      }
    }
  },

  loadGoodsListData:function(cpage){
    var that = this;
    var goodsTypeId = that.data.selectCata.goods_id;
    var gtype = that.data.selectCata.goods_id ;
    loadingMore = true;
    var zhiding = that.data.selectCata.zhiding ? that.data.selectCata.zhiding : '';
    var num = that.data.selectCata.num ? that.data.selectCata.num : '10';
    var params = {
      publickey: util.publiccode,
      ac: util.orgid == 18681 || util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484
 ?"topiclistwithguige":"topiclist",
      topictype: '4',
      orgid: util.orgid,
      toporder: that.data.toporder,
      zhiding: zhiding,
      page: cpage.toString(),
      gtype: gtype,
      pin: that.data.pinSign,
      sellprice: price,
      hot: hot,
      num: num
    };
    
    console.log("商店商品请求参数：", params);
    util.api({
      data:params,
      success:function(responseData){
        console.log("商店商品数据:",responseData);
        var resData=responseData.data;
        var newData='';
        if(resData.msg){
          hasMore = false;
          if (cpage<=1){
            that.setData({
              goodsList: [],
            });
          };
        }else{
          if(cpage>1){
            newData=that.data.goodsList.concat(resData);
          }else{
            newData=resData;
          };
          var gwc_datas = wx.getStorageSync('gwc_datas');

          if (!gwc_datas) {
            gwc_datas = [];
          }
          gwc_datas.forEach(function(m,i){
            for(var j=0;j<newData.length;j++){
              var n=newData[j];
              if (0&&n.guigelist) {
                for (var k = 0; k < n.guigelist.length; k++) {
                  if (m.selGuige.id == n.guigelist[k].id) {
                    n.guigelist[k].selectednum = m.buycount;
                  }

                }

              } else {
                if (m.id == n.id) {
                  n.selectednum = m.buycount;

                }
              }
            }
          })
          that.setData({
            goodsList:newData,
          });
          that.updateSwiperHeight();
          if (util.orgid == '12545') {

            that.markGoodsListWithRec();
            that.markGoodsList();
          }
          allGoodsData[goodsTypeId]=newData;
          //列表中分类是否存在
          var existGoodsTypeId = false;
          var allGoodsDataArray = that.data.allGoodsDataArray;
          for (var m = 0; m < allGoodsDataArray.length;m++){
            if (allGoodsDataArray[m].goods_id == goodsTypeId){
              existGoodsTypeId=true;
              if (!allGoodsDataArray[m].goodsList) {
                allGoodsDataArray[m].goodsList = [];

              }
              allGoodsDataArray[m].goodsList = that.data.goodsList;
            }
          }
          //列表中分类不存在，添加
          if (!existGoodsTypeId){
            let obj = {};
            obj.goods_id = goodsTypeId;
            obj.goodsList = that.data.goodsList;
            allGoodsDataArray.push(obj);
          }
          that.setData({
            allGoodsDataArray: allGoodsDataArray
          })
          that.loadCatadataCounts();
          console.log("allGoodsData:",allGoodsData);
          console.log("allGoodsDataArray:", allGoodsDataArray);
        }
        loadingMore=false;
        if (cpage <= 1 && that.data.goodsList.length <= 0) {
          that.setData({
            noData: true
          });
        };
        
        wx.hideLoading();
      }
    });
  },




  showType: function (event) {
    var that = this;
    this.setData({
      hidecata: !that.data.hidecata
    })
  },

  

  priceOrder: function () {
    hot = 0;
    page = 1;
    if (price == 0 || price == 1) {
      price = 2;
    } else {
      price = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    this.loadGoodsListData(1);
  },
  hotOrder: function () {
    price = 0;
    page = 1;
    if (hot == 0 || hot == 1) {
      hot = 2;
    } else {
      hot = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      toporder: '',
      hidecata: true
    });
    this.loadGoodsListData(1);
  },



  goAtherPage: function (e) {
    
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  //点击左侧菜单切换
  changeCata: function(event) {

    if (loadingMore) {
      return false;
    }

    price = 0;
    hot = 0;
    var that = this;
    var cataid = event.currentTarget.dataset.cataid;
    var cataindex = event.currentTarget.dataset.index;
    console.log(cataid, cataindex);
    page = 1;
    hasMore = true;
    loadingMore = false;
    that.setData({
      // infodata: dataall[cataindex]['child'] ? dataall[cataindex]['child'] : [],
      selectCata: dataall[cataindex],
      gcataid: dataall[cataindex]['goods_id'].substring(0,3),
      currcata: cataindex,
      currView: cataindex,
      nowcata: dataall[cataindex].child,
      searchVal: '',
      toporder: '1',
      hidecata: true,
      priceorder: 0,
      hotorder: 0,
      goodTypeName: '',
      noData: false
    });
    console.log("gcataid:changeCata|||||||||||||" + that.data.gcataid);
    var goodsTypeId = that.data.selectCata.goods_id;
    var data = allGoodsData[goodsTypeId];
    console.log("goodsType = " + goodsTypeId + "; data = " + data);
    if(data && data.length > 0){

      var gwc_datas = wx.getStorageSync('gwc_datas');
      if (!gwc_datas) {
        gwc_datas = [];
      }
      gwc_datas.forEach(function (m, i) {
        for (var j = 0; j < data.length; j++) {
          var n = data[j];
          if (0&&n.guigelist) {
            for (var k = 0; k < n.guigelist.length; k++) {
              if (m.selGuige.id == n.guigelist[k].id) {
                n.guigelist[k].selectednum = m.buycount;
              }

            }

          }else{
            if (m.id == n.id) {
              n.selectednum = m.buycount;

            }
          }
        }
      })
      that.setData({
        goodsList: data,
      });
      allGoodsData[goodsTypeId] = data;
      that.data.allGoodsDataArray[that.data.currcata].goodsList = that.data.goodsList
      that.setData({
        goodsList: that.data.goodsList,
        allGoodsDataArray: that.data.allGoodsDataArray
      })

      that.markGoodsListWithRec();
      that.markGoodsList();
      //列表中分类是否存在

      //总列表中更新
      var allGoodsDataArray = that.data.allGoodsDataArray;
      var existGoodsTypeId = false;
      for (var m = 0; m < allGoodsDataArray.length; m++) {
        if (allGoodsDataArray[m].goods_id == goodsTypeId) {
          existGoodsTypeId = true;
          if (!allGoodsDataArray[m].goodsList) {
            allGoodsDataArray[m].goodsList = [];

          }
          allGoodsDataArray[m].goodsList = that.data.goodsList;
        }
      }
      //列表中分类不存在，添加
      if (!existGoodsTypeId) {
        let obj = {};
        obj.goods_id = goodsTypeId;
        obj.goodsList = that.data.goodsList;
        allGoodsDataArray.push(obj);
      }
      that.setData({
        allGoodsDataArray: allGoodsDataArray
      })
    } else {
      if (util.orgid != 21145 && util.orgid != 21398 && util.orgid != 21484) {
        wx.showLoading({
          title: that.data.tc == 1 ? '加載中' : '加载中',
          mask:'true'
        })
        that.loadGoodsListData(1);
      }
    }

    that.updateSwiperHeight();
  },
  // 滑块切换标签样式
  switchTab: function (e) {
    var that=this
    console.log("e",e)
    this.setData({
      currcata: e.detail.current,
    });
    e.currentTarget.dataset.cataid = this.data.allGoodsDataArray[e.detail.current].goods_id;
    e.currentTarget.dataset.index = e.detail.current;

    this.changeCata(e);
    this.checkCor();
    that.updateSwiperHeight()
  },
  
  switchTabNav: function (e) {
    console.log("e",e)
    if (e.detail.source == "touch") {
      console.log("e.detail.source")
      this.setData({
        tabcurrcata: e.detail.current,
      });

    }
    
  },


  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    var len=0;
    var currcata=this.data.currcata
    var catadata = this.data.catadata
    for(var i=0;i<currcata;i++){
      len+=catadata[i].cname.length;
    }
    console.log('currcata--->len======',len)
    if (util.orgid == '12545') {
      this.setData({
        scrollLeft: 300 * parseInt(len / 16)
      })
      // this.setData({
      //   toView: 'cataitem' + currcata
      // })


    } else if (util.orgid == '14939'){
      this.setData({
        scrollLeft: 300 * parseInt(this.data.currcata / 4)
      })

    }
  },

  //判断商品是否有属性
  getAttribute:function(e){
    var that = this;
    
    var good = e.currentTarget.dataset.good;
    console.log("Good",e.currentTarget.dataset.good);
    console.log("addGoods",e.currentTarget.dataset.good.groupId);
    if (good.kucun <= 0) {
      wx.showToast({
        title: that.data.tc == 1 ? '庫存為空' : '库存为空',
      });
      return;
    }else{
      var group = e.currentTarget.dataset.good.groupId;
      if (group == 0) {
        if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484){
          if (!good.guigelist) {
            that.addGoods(e);

          }
        } else {
          that.addGoods(e);

        }
      } else {
        that.showModal();
        var params = {
          publickey: util.publiccode,
          ac: "getAttribute",
          orgid: util.orgid,
          uid: that.data.uid,
          groupId: group
        };

        console.log("商品属性请求参数：", params);
        util.api({
          data: params,
          success: function (responseData) {
            console.log("商品属性:", responseData.data);
            var result = responseData.data;
            if (result.length > 0) {
              var groups = [];
              for (var i = 0; i < result.length; i++) {
                var exist = false;
                if (i == 0) {
                  let groupObj = { groupId: '', groupName: "", subList: [] };
                  groupObj.groupId = result[i].groupId;
                  groupObj.groupName = result[i].groupName;
                  let subObj = {};
                  subObj.attributeId = result[i].attributeId;
                  subObj.attributeName = result[i].attributeName;
                  subObj.checked = false;
                  subObj.counts = 0;
                  groupObj.subList.push(subObj);
                  groups.push(groupObj);
                  continue
                } else {
                  for (var j = 0; j < groups.length; j++) {
                    if (groups[j].groupId == result[i].groupId) {
                      let subObj = {};
                      subObj.attributeId = result[i].attributeId;
                      subObj.attributeName = result[i].attributeName;
                      subObj.checked = false;
                      subObj.counts = 0;
                      groups[j].subList.push(subObj);
                      exist = true;
                      break
                    }
                  }
                  if (!exist) {
                    let groupObj = { groupId: '', groupName: "", subList: [] };
                    groupObj.groupId = result[i].groupId;
                    groupObj.groupName = result[i].groupName;
                    let subObj = {};
                    subObj.attributeId = result[i].attributeId;
                    subObj.attributeName = result[i].attributeName;
                    subObj.checked = false;
                    groupObj.subList.push(subObj);
                    groups.push(groupObj);
                  }

                }


              }
              console.log('groups---->', groups);

              good.attributeGroups = groups;
              that.setData({
                childArr: [],
                attributeGroupsOriginal: result,
                mainfoodArray: [],
                drinksArray: [],
                prefoodArray: [],
                attributeGroups: groups,
                // showAttributeNew: true,
                showAttribute: true,
                good: good
              });
              that.markAttrGroups();
              that.prefoodInitial();
            }
          }
        });
      };

    }
    
  },

  addGoodsWithAttr(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    


    var that = this;
    var prefoodArray = that.data.prefoodArray;
    var mainfoodArray = that.data.mainfoodArray;
    var drinksArray = that.data.drinksArray;
    var array = [];
    array = array.concat(prefoodArray);
    array = array.concat(mainfoodArray);

    array =array.concat(drinksArray);
    // if (drinksArray.length > 0 && prefoodArray.length > 2 && mainfoodArray.length>0){
      // var groups = e.detail.value;
      // var Groups = that.data.attributeGroups;
      // var array = [];
      // var i = 0;
      // for (var key in groups) {
      //   var itemValue = groups[key];
      //   if (itemValue) {
      //     for (var k = 0; k < Groups.length; k++) {
      //       console.log("Groups[i].subList数据： ", Groups[k].subList);
      //       let subList = Groups[k].subList;
      //       for (var j = 0; j < subList.length; j++) {

      //         if (Groups[k].groupId == key && Groups[k].subList[j].attributeId == itemValue) {
      //           let itemOb = {};
      //           itemOb.groupId = key;
      //           itemOb.groupName = Groups[k].groupName;

      //           itemOb.attributeId = itemValue;
      //           itemOb.attributeName = Groups[k].subList[j].attributeName;
      //           array[i] = itemOb
      //           ++i;

      //         }
      //       }
      //     }

      //   }
      //   console.log("groups数据： ", key + ':' + groups[key]);
      // }

      console.log("groupsarray： ", array);
      console.log("that.data.attributeGroups： ", that.data.attributeGroups);
      that.data.good.attribute = array;
      
      if (array.length < that.data.attributeGroups.length-1 || (array.length < 7 && that.data.good.gtype =='412440')){

        wx.showModal({
          title: '請選擇完整',
          content: '',
        })
      } else {
        if (this.data.showAttribute == true) {

          that.hideModal();
          that.setData({
            showAttribute: false
          })
        }
        that.addGoods(e);
      }
    // }
    // else if (drinksArray.length == 0 || prefoodArray.length == 2 || mainfoodArray.length == 0) {
    //   wx.showModal({
    //     title: '',
    //     content: '請選擇您的套餐',
    //   })
    // }   
    
  },
   //加入购物车
  addGoods:function(e){
    console.log('form发生了submit事件，携带数据为：', e.detail)
    console.log('add事件，携带数据为：', e.currentTarget.dataset.guige)
    // console.log('.attribute携带数据为：', this.data.good.attribute);
    console.log('this.data.good携带数据为：', this.data.good);
    var that = this;
    if (this.data.showAttribute == true) {
      that.setData({
        showAttribute: false
      })

    }
    var good = e.currentTarget.dataset.good ? e.currentTarget.dataset.good : that.data.good;
    if (good.kucun<=0){
      wx.showToast({
        title: that.data.tc == 1 ? '庫存為空' : '库存为空',
      });
      return;
    }else{
      if (this.data.countValue >= good.kucun) {
        wx.showToast({
          title: that.data.tc == 1 ? '超出庫存啦' : '超出库存啦',
        });
        return;
      }
       //获取规格商品
      
      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "goodsguige",
          "goods_id": good.id
        },
        success: function (responseData) {
          console.log("addgoods商品规格：", responseData.data)
          if (!responseData.data.msg) {
            var selGuige = responseData.data[0];
            that.setData({
              guigeData: responseData.data,
              selectGuige: e.currentTarget.dataset.guige ? e.currentTarget.dataset.guige:selGuige
            })
          }else{
            that.setData({
              guigeData: [],
              selectGuige: ''
            })
          }
       

          var gwc_datas = wx.getStorageSync('gwc_datas');
          if (!gwc_datas) {
            gwc_datas = [];
          }

          var goodsInfo = {};
          goodsInfo.id = good.id;
          goodsInfo.ghsid = good.postuid;
          goodsInfo.title = good.topictitle;
          goodsInfo.titleofenglish = good.titleofenglish;
          goodsInfo.def_img = good.photoscbk ? good.photoscbk[0].photo : '';
          goodsInfo.sel = true;
          goodsInfo.guigeName = that.data.selectGuige.name ? that.data.selectGuige.name : '';
          goodsInfo.selGuige = that.data.selectGuige;
          if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484&& good.selGuige){
            goodsInfo.selGuige = good.selGuige;
          }
          if (good.pin == 1) {//拼单商品
            goodsInfo.price = good.pinprice;
          } else {
            goodsInfo.price = that.data.selectGuige ? that.data.selectGuige.price : good.sellprice;
          }
          goodsInfo.yunfei = good.yunfei;
          goodsInfo.kucun = good.kucun;
          goodsInfo.buycount = that.data.countValue;
          goodsInfo.source = good.source;
          goodsInfo.pin = good.pin;//这里加是否是拼单商品标记
          goodsInfo.pinzong = good.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
          goodsInfo.linkcode = good.linkcode;//商品唯一32位id
          goodsInfo.attribute = good.attribute ? good.attribute : '';//商品属性
          goodsInfo.groupId = good.groupId;
          goodsInfo.titleArray = good.titleArray;
          goodsInfo.RecMark = good.RecMark;


          var addItem = [goodsInfo];
          console.log("addItem==", addItem);
          var hasSameGoods = false;

          //获取规格商品
          // that.getGuigeData(good.id);

          if (util.orgid != '12545') {
            if (gwc_datas.length > 0) {
              for (var i = gwc_datas.length - 1; i >= 0; i--) {
                if (gwc_datas[i].id == goodsInfo.id) {
                  if (that.data.guigeData.length > 0) {
                    if (gwc_datas[i].selGuige.id == goodsInfo.selGuige.id) {
                      hasSameGoods = true;
                      gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
                    }
                  } else {
                    hasSameGoods = true;
                    gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
                  }
                }
              }
            }
          }

          if (!hasSameGoods) {
            gwc_datas = addItem.concat(gwc_datas);
            var count = that.data.gwc_count + 1;
            that.setData({
              gwc_count: count
            })

          }

          console.log("gwc_datas====:" + gwc_datas);
          console.log("gwc_datas====:" + gwc_datas.length);
          that.calTotalPrice();
          wx.setStorageSync('gwc_datas', gwc_datas);

          that.setData({
            gouwucheData: gwc_datas,
          })
          that.calTotalPrice();
          var contentname = that.data.tc == 1 ? '已成功加到購物車' : '已成功加到购物车';
          wx.showToast({
            title: contentname,
          });
          that.data.goodsList.forEach(function(m,i){
            if (m.id == good.id){
              if (0&&m.guigelist) {
                m.guigelist.forEach(function (n, j) {
                  if (n.id == e.currentTarget.dataset.guige.id) {
                    if (!n.selectednum) {
                      n.selectednum = 0
                    }
                    n.selectednum++;
                    console.log("selectednum++")
                    
                    that.data.allGoodsDataArray[that.data.currcata].goodsList = that.data.goodsList
                    that.setData({
                      goodsList: that.data.goodsList,
                      allGoodsDataArray: that.data.allGoodsDataArray
                    })
                  }
                })  

              }else{
                if (!m.selectednum) {
                  m.selectednum = 0
                }
                m.selectednum++;
                console.log("selectednum++")
                if (!that.data.catadata[that.data.currcata].counts){
                  that.data.catadata[that.data.currcata].counts=0
                }
                that.data.catadata[that.data.currcata].counts++;
                allGoodsData[that.data.selectCata.goods_id] = that.data.goodsList;
                that.data.allGoodsDataArray[that.data.currcata].goodsList = that.data.goodsList
                console.log("catadata==1==",that.data.catadata);
                that.setData({
                  catadata: that.data.catadata,
                  goodsList: that.data.goodsList,
                  allGoodsDataArray: that.data.allGoodsDataArray
                })

                that.loadCatadataCounts()
              }
            }
          })
        }
      }); 
    // var newInputValue = this.data.countValue + 1;
    // this.setData({
    //   countValue: newInputValue
    // })
    }
    
  
  },

  minusGoods: function (e){
    console.log("minusgoods")
    var that=this;
    var gwc_datas = wx.getStorageSync('gwc_datas');
    var good=e.currentTarget.dataset.good;
    var guige=e.currentTarget.dataset.guige;
    for (var i = gwc_datas.length - 1; i >= 0; i--) {
      if (gwc_datas[i].id == good.id) {
        // if (gwc_datas[i].selGuige.id == guige.id) {
        gwc_datas[i].buycount = gwc_datas[i].buycount -1;
        if(gwc_datas[i].buycount==0){
          gwc_datas.splice(i, 1);
          that.setData({
            gwc_count: that.data.gwc_count - 1 < 0 ? 0 : (that.data.gwc_count - 1)
          })
        }
        that.setData({
          gouwucheData: gwc_datas,
        })
        wx.setStorageSync('gwc_datas', gwc_datas);
        that.calTotalPrice();
        // }
      }
    }

    
    that.data.goodsList.forEach(function (m, i) {
      if (m.id == good.id) {
        if (0 &&m.guigelist) {
          m.guigelist.forEach(function (n, j) {
            if (n.id == e.currentTarget.dataset.guige.id) {
              if (n.selectednum > 0) {
                n.selectednum--;
                that.setData({
                  goodsList: that.data.goodsList
                })
              }

              console.log("selectednum--")


            }
          })

        } else {
          if (m.selectednum > 0) {
            m.selectednum--;

            console.log("selectednum--")

            that.data.catadata[that.data.currcata].counts--;
            allGoodsData[that.data.selectCata.goods_id] = that.data.goodsList;
            that.data.allGoodsDataArray[that.data.currcata].goodsList = that.data.goodsList
            console.log("catadata==2==",that.data.catadata);
            that.setData({
              catadata: that.data.catadata,
              goodsList: that.data.goodsList,
              allGoodsDataArray: that.data.allGoodsDataArray
            })
            that.loadCatadataCounts()
          }
        }
      }
    })
  },

  //减少动作
  reduceAction: function (e) {
    var that = this
    var index = e.currentTarget.dataset.itemid;
    var gwc_datas = wx.getStorageSync('gwc_datas');
    var newInputValue = gwc_datas[index].buycount - 1
    // if (newInputValue < 1) {
    //   return;
    // }
    gwc_datas[index].buycount = newInputValue;
    if (gwc_datas[index].buycount == 0) {
      gwc_datas.splice(index, 1);
      that.setData({
        gwc_count: that.data.gwc_count - 1 < 0 ? 0 : (that.data.gwc_count - 1)
      })
    }
    that.setData({
      gouwucheData: gwc_datas,
    })
    wx.setStorageSync('gwc_datas', gwc_datas);
    this.calTotalPrice();
  },
  //增加动作
  addAction: function (e) {
    var that=this
    var index = e.currentTarget.dataset.itemid;
    var gwc_datas = wx.getStorageSync('gwc_datas');
    var newInputValue = gwc_datas[index].buycount + 1
    if (newInputValue > gwc_datas[index].kucun) {
      var titlename = this.data.tc == 1 ? '超出庫存啦' : '超出库存啦';
      wx.showToast({
        title: titlename,
      });
      newInputValue = gwc_datas[index].kucun;
    }
    gwc_datas[index].buycount = newInputValue;
    that.setData({
      gouwucheData: gwc_datas,
    })
    wx.setStorageSync('gwc_datas', gwc_datas);
    this.calTotalPrice();
  },

  getGuigeData: function (g_id) {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodsguige",
        "goods_id": g_id
      },
      success: function (responseData) {
        console.log("商品规格：", responseData.data)
        if (!responseData.data.msg) {
          var selGuige = responseData.data[0];
          that.setData({
            guigeData: responseData.data,
            selectGuige: selGuige
          })
        }
      }
    });
  },

  //跳转
  goAtherPageReList: function (e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    // if (util.orgid != '12545' && util.orgid != '13078' && util.orgid != '15938' && util.orgid != '16708' &&wxAuthFail && (url.indexOf('gouwuche/gouwuche') >= 0)) {
    //   app.reAuthorize(this.reGetUserInfo);
    //   return;
    // }
    // wx.reLaunch({ url: url});
    wx.navigateTo({ url: url});
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  getLoginInfo:function(){
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        console.log("daying"+res.uid);
        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })

        that.load();

      } else {
        that.load();
        wxAuthFail = true;
      }
    }, inviteuid)
  },


   load:function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      linkcode: linkcode,
      inviteuid: inviteuid,
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
        data:params,
        success:function(responseData){  
            var data = responseData.data;
            console.log("啊啊啊啊啊详情：", data);

            //获取规格商品
            that.getGuigeData(data.id);

            //供货商信息
            if (data.orgid) {
              app.GetUserInfo(data.orgid, function (res) {
                console.log("供货商信息：", res);
                that.setData({
                  ghs_info: res
                })
              });
            }

            //处理时间
            var date = new Date(data.dateline*1000);
            data.formatDate = date.getFullYear()+"-"+(Number(date.getMonth())+1)+"-"+date.getDate();
            //处理语音
            if(data.audio) {                
                data.formatAudio = JSON.parse(data.audio);
            }
            //处理视频
            if (data.video) {
              var videolinks = data.video.split(",");
              var len = videolinks.length;
              var tx_videolinks = [];
              for (var i = 0; i < len; i++) {
                if (videolinks[i].indexOf('v.qq.com') > 0) {
                  tx_videolinks = tx_videolinks.concat(videolinks[i])
                }
              }
              len = tx_videolinks.length;
              var videoSrcs = new Array(len);
              var count = 0;
              for (var i = 0; i < len; i++) {
                app.getVideoSrcLink(i, tx_videolinks[i], function (url, index) {
                  count++;
                  if (url != -1) {
                    videoSrcs[index] = url;
                  }
                  if (count >= len) {
                    var videoSrcArr = [];
                    for(var n = 0; n < len; n++){
                      if(videoSrcs[n]){
                        videoSrcArr = videoSrcArr.concat(videoSrcs[n]);
                      }
                    }
                    that.setData({
                      videolinkArray: videoSrcArr
                    });
                  }
                  
                });
              }
            }
            //处理message  
            detailMessage = data.message;
            // detailMessage = data.message.replace(/\n/g, '<br />');
            console.log("detailMessage: ", detailMessage);
            
            that.setData({
              detailMessage: data.message,
            }); 
            /** 
            * WxParse.wxParse(bindName , type, data, target,imagePadding) 
            * 1.bindName绑定的数据名(必填) 
            * 2.type可以为html或者md(必填) 
            * 3.data为传入的具体数据(必填) 
            * 4.target为Page对象,一般为this(必填) 
            * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
            */
            WxParse.wxParse('detailMessage', 'html', detailMessage, that, 12); 
            // data.message = data.message.replace(/&nbsp;/g, '');
            
            topictitle = data.topictitle;
            uname = data.user.username;
            
            var f_imgUrl = '';
            if (data.photoscbk && data.photoscbk.length > 0){
              var firstImageInfo = data.photoscbk[0];
              if (firstImageInfo) {
                f_imgUrl = firstImageInfo.photo + "!120a";
              }
            }
            console.log("第一张图片链接：", f_imgUrl);
            that.setData({
                data:data,
                likeuser: data.likeuser,
                isLiked:data.isLiked,
                tuid:data.postuid,
                firstImgUrl: f_imgUrl
            });          
           //当前用户是否已关注作者
            that.isFollow(uid, data.postuid);
            //当前用户是否已赞该动态
            that.isLike(uid);
            wx.hideLoading();

        }
    });
    //拼单列表
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"getgoodspin",
            goods_id:topicid,
        },
        success:function(responseData){                 
            var data = responseData.data;
            console.log("历史拼单：", data);
            if(!data.msg){
              var keys = [];
              for (var key in data) {
                keys.push(key);
              }
              var pinArray = [];
              var index = 0;
              for (var i = keys.length - 1; i >= 0; i--) {
                pinArray[index] = [];
                pinArray[index] = data[keys[i]];
                index++;
              }
              console.log("历史拼单array：", pinArray);
              if (pinArray.length > 0) {
                that.setData({
                  pinHistoryData: pinArray
                });
              }  
            }           
        }
    });
    
    this.loadCommentList(topicid, 1);
  },

  //读取所有评论
  loadCommentList: function(gid, page){
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "ordercommentall",
        goods_id: gid,
        page: page,
        num:10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("商品评论：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.pinglun.date = util.formatTime(new Date(parseInt(m.pinglun.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },

  //立即购买
   buyAction: function (e) {
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    var allSel = true;
    if(gwc_datas.length > 0){
      var ghsid_0 = gwc_datas[0].ghsid;
      gwc_datas.forEach(function (m, i) {
        m.left = 0;
        if (m.ghsid != ghsid_0){
          m.sel = false;
          allSel = false;
        }
      });
      this.setData({
        gouwucheData: gwc_datas,
        // jisuanCount: gwc_datas.length,
        // totalSel: allSel
      });
      this.calTotalPrice();
    }
    var allData = this.data.gouwucheData;
    var jiesuanArr = [];
    if(!allData){
      var contentname = this.data.tc == 1 ? '請先選擇商品' : '请先选择商品';
      wx.showModal({  
          title: '提示',  
          content: contentname, 
          confirmText: this.data.tc == 1 ? '確定' : '确定',
          showCancel: false,//去掉取消按钮  
        }) 
      
    }else{
      for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        jiesuanArr = jiesuanArr.concat(allData[i]);
        }
      }
      var jieSuanStr = JSON.stringify(jiesuanArr);
      var url = "/pages/order-confirm/order-confirm?goodsArr=" + jieSuanStr;
      wx.navigateTo({ url: url });
    }
    
  },

  //处理总价
  calTotalPrice: function(){
    var allData =  wx.getStorageSync('gwc_datas');
    var allPrice = 0;
    var count = 0;
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        allPrice += allData[i].price * allData[i].buycount;
        allPrice += parseInt(allData[i].yunfei) * 100;
        count++;
      }
    }
    this.setData({
      totalPrice: allPrice,
      youhuiPrice: 0,
      jisuanCount: count
    });
  },


  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },


  //查询领号等待数
  getWaithao:function(){
    var that = this;
    //查询领号等待数
    var privatekey = utilMd5.hexMD5(that.data.uid + 'waithao' + that.data.token);
    console.log("that.data.uid:"+that.data.uid+"that.data.token:"+that.data.token+"util.orgid:"+util.orgid);
     util.api({
      method: "post",
      data: {
        ac: "waithao",
        uid: that.data.uid,
        orgid: that.data.postuid, 
        privatekey: privatekey
      },
      
      success: function (responseData) {
        console.log("调试--查询领号等待数接口:", responseData.data);
        that.setData({
          waithao: responseData.data,
        });
        
      }
    });
  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == "15671") {
      return {
        title: '求职，企业招聘，人才培训……壹号人才欢迎您',
        path: '/pages/talent-index/talent-index?&inviteuid=' + inviteuid
      };

    } else if (util.orgid == "18535") {
      return {
        // title: that.data.titlename+'公寓新开业，88特价房，无敌江景、超正夜景',
        title: that.data.titlename +'公寓新开业，超级无敌优惠酬宾啊！',
        path: '/pages/goodslist/goodslist?&inviteuid=' + inviteuid + '&uid=' + that.data.ghs.uid + '&logo_url=' + that.data.ghs.avatar + '&gcataid=' + that.data.ghs.gcataid + '&username=' + that.data.ghs.username
      };

    } else{
      return {
        title: that.data.org_name,
        path: '/pages/goodslist/goodslist?&inviteuid=' + inviteuid + '&uid=' + that.data.ghs.uid + '&logo_url=' + that.data.ghs.avatar + '&gcataid=' + that.data.ghs.gcataid + '&username=' + that.data.ghs.username
      };

    }
  },


  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    var that=this;
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    this.setData({
      gwc_count: gwc_datas.length
    });
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    if (util.orgid == 18681 || util.orgid == 12809 || util.orgid == 21780) {
      var gwc_count = 0;
      gwc_datas.forEach(function (m, i) {
        gwc_count += m.buycount
      })
      this.setData({
        gwc_count_aoka: gwc_count
      });

    }

    that.updateSwiperHeight();
    that.calTotalPrice();

  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  hideAttribute: function () {
    var that=this;
    that.hideModal();

  },
  radioChange: function (e) {
    var that=this
    console.log('radio发生change事件，携带value值为：', e.currentTarget.dataset)
    var Groups = this.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++){
        if (Groups[i].groupId == e.currentTarget.dataset.groupid.substring(0,3) && Groups[i].subList[j].attributeId == e.currentTarget.dataset.value) {

          if (Groups[i].groupId == e.currentTarget.dataset.groupid){
            Groups[i].subList[j].checked = true;
          }
          
          that.checkChildArray(e);
          var childArr = that.data.childArr;
          for (var k = 0; k < childArr.length; k++) {
            if (childArr[k].groupId == e.currentTarget.dataset.groupid && childArr[k].attributeId == e.currentTarget.dataset.value) {
              childArr[k].checked = true;
            }
          }
          that.setData({
            childArr: childArr
          })

          if (e.currentTarget.dataset.groupid.substring(0, 3) == '300') {
            that.addDrink(e)
          } 
          if (e.currentTarget.dataset.groupid == '200') {
            that.addMainfood(e)
          } 
          if (e.currentTarget.dataset.groupid == '100') {
            that.addprefood(e)
          }
            // if (e.currentTarget.dataset.groupid == '300' && e.currentTarget.dataset.value==10){
            //   that.showAttributeChild(e)
              
            // }
        } else if (Groups[i].groupId == e.currentTarget.dataset.groupid){
          Groups[i].subList[j].checked = false
        }
      }
        
    }

    this.setData({
      attributeGroups: Groups,
    });


  },

  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.currentTarget.dataset)
    var Groups = this.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (Groups[i].groupId == e.currentTarget.dataset.groupid && Groups[i].subList[j].attributeId == e.currentTarget.dataset.value) {
          if (Groups[i].subList[j].checked == false) {
            Groups[i].subList[j].checked = true
          }else{
            Groups[i].subList[j].checked = false
          }
        } else if (Groups[i].groupId == e.currentTarget.dataset.groupid) {
          
        }
      }

    }

    this.setData({
      attributeGroups: Groups
    });


  },
  showPrefood: function () {
    if (!this.data.showPrefood) {
      this.setData({
        showPrefood: true
      })
    } else {
      this.setData({
        showPrefood: false
      })
    }

  },
  showMainfood: function () {
    if (!this.data.showMainfood) {
      this.setData({
        showMainfood: true
      })
    } else {
      this.setData({
        showMainfood: false
      })
    }

  },
  showDrink: function () {
    if (!this.data.showDrink) {
      this.setData({
        showDrink: true
      })
    } else {
      this.setData({
        showDrink: false
      })
    }

  },

  addDrink(e){
    var that=this;
    console.log('addDrink',e.currentTarget.dataset);
    var Groups= that.data.attributeGroups;
    var drinksArray = that.data.drinksArray;
    that.data.addDrink=true;

    for (var i = 0; i <Groups.length;i++){
      for (var j = 0; j < Groups[i].subList.length; j++) {
        console.log('substring(4, 5)', e.currentTarget.dataset.groupid.substring(4, 5));
        if (e.currentTarget.dataset.groupid.length > 3 && e.currentTarget.dataset.groupid.substring(0, 3) == Groups[i].groupId && e.currentTarget.dataset.groupid.substring(4, 5) == Groups[i].subList[j].attributeId) {
          //二级字串
          console.log('e.currentTarget.dataset.groupid.substring(0, 3)', e.currentTarget.dataset.groupid)
          let itemOb = {};
          itemOb.groupId = e.currentTarget.dataset.groupid;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = e.currentTarget.dataset.value;
          itemOb.attributeName = e.currentTarget.dataset.attributename;
          itemOb.attributeNameEng = e.currentTarget.dataset.attributenameeng;

          if (that.data.good.gtype == '412440' && drinksArray.length < 2) {
            drinksArray.push(itemOb);
            console.log('add1')
          } else if (that.data.good.gtype != '412440' && drinksArray.length < 1) {
            drinksArray.push(itemOb);
            console.log('add2')
          } else {
            console.log('add3')
            drinksArray.push(itemOb);
            drinksArray.splice(0, 1);
          }

        } else if (that.data.existChildArr==false&&e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;
          

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (that.data.good.gtype == '412440' && drinksArray.length < 2){
            drinksArray.push(itemOb);
          } else if (that.data.good.gtype != '412440' &&drinksArray.length < 1) {
            drinksArray.push(itemOb);

          }else{
            drinksArray.push(itemOb);
            drinksArray.splice(0,1);
          }
        } else {

        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('drinksArray', drinksArray)
    this.setData({
      attributeGroups: Groups,
      drinksArray: drinksArray
    });


  },

  delDrink:function(e){
    console.log('delDrink', e.currentTarget.dataset);
    var that=this;
    var drinksArray=that.data.drinksArray;
    for (var i = 0; i < drinksArray.length;i++){
      if (i == e.currentTarget.dataset.idx ){
        drinksArray.splice(i,1);
      }
    }
    console.log('drinksArray', drinksArray)
    this.setData({
      drinksArray: drinksArray
    });

  },
  addMainfood(e) {
    var that = this;
    console.log('addDrink', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var mainfoodArray = that.data.mainfoodArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (mainfoodArray.length < 2) {
            mainfoodArray.push(itemOb);

          } else {
            mainfoodArray.push(itemOb);
            mainfoodArray.splice(0, 1);
          }
        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('mainfoodArray', mainfoodArray)
    this.setData({
      attributeGroups: Groups,
      mainfoodArray: mainfoodArray
    });


  },

  delMainfood: function (e) {
    console.log('delMainfood', e.currentTarget.dataset);
    var that = this;
    var mainfoodArray = that.data.mainfoodArray;
    for (var i = 0; i < mainfoodArray.length; i++) {
      if (i == e.currentTarget.dataset.idx) {
        mainfoodArray.splice(i, 1);
      }
    }
    console.log('mainfoodArray', mainfoodArray)
    this.setData({
      mainfoodArray: mainfoodArray
    });

  },

  addprefood(e) {
    var that = this;
    console.log('addprefood', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var prefoodArray = that.data.prefoodArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (prefoodArray.length < 3) {
            prefoodArray.push(itemOb);

          } else {
            prefoodArray.push(itemOb);
            prefoodArray.splice(2, 1);
          }
        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('addprefood', prefoodArray)
    this.setData({
      attributeGroups: Groups,
      prefoodArray: prefoodArray
    });


  },

  delprefood: function (e) {
    console.log('delprefood', e.currentTarget.dataset);
    var that = this;
    var prefoodArray = that.data.prefoodArray;
    for (var i = 2; i <3; i++) {
      if (i == e.currentTarget.dataset.idx) {
        prefoodArray.splice(i, 1);
      }
    }
    console.log('prefoodArray', prefoodArray)
    this.setData({
      prefoodArray: prefoodArray
    });

  },
  prefoodInitial(){
    var that = this;
    var Groups = that.data.attributeGroups;
    var prefoodArray = that.data.prefoodArray;
    console.log('prefoodArrayIntial', prefoodArray)
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (Groups[i].groupId == '100' && (Groups[i].subList[j].attributeId == '5' || Groups[i].subList[j].attributeId== '4')) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          prefoodArray.push(itemOb);
        }
      }
      
    }
    console.log('prefoodArrayIntial', prefoodArray)
    this.setData({
      prefoodArray: prefoodArray
    });
  },


  markGoodsList:function(){
    var that=this;
    var goodsList=that.data.goodsList;
    for (var i = 0; i < goodsList.length; i++) {
      let title = goodsList[i].topictitle;
      
      if (title.indexOf("+") > 0){
        //多个子标题
        let navArr = title.split('+');
        console.log('titleArr', navArr)
        for (var j = 0; j < navArr.length; j++) {
          let subStr = navArr[j];
          if (subStr.indexOf("|") > 0) {
            //标题有标志
            let miniArr = subStr.split('|')
            if(!goodsList[i].titleArray){
              goodsList[i].titleArray = []; 
            }
            let obj={}
            obj.title = miniArr[0];
            obj.mark = miniArr[1];
            // 英文标题
            if (obj.title.indexOf('\\')>0){
              let langArr = obj.title.split('\\');
              obj.title = langArr[0];
              obj.titleEnglish = langArr[1];
            } else {
              obj.titleEnglish = '';
            }
            goodsList[i].titleArray.push(obj);            
            console.log('topictitle.mark', goodsList[i].titleArray)
          }else{
            if (!goodsList[i].titleArray) {
              goodsList[i].titleArray = [];
            }
            let obj = {}
            obj.title = subStr;
            obj.mark = '';
            // 英文标题
            if (obj.title.indexOf('\\') > 0) {
              let langArr = obj.title.split('\\');
              obj.title = langArr[0];
              obj.titleEnglish = langArr[1];
            } else {
              obj.titleEnglish = '';
            }
            goodsList[i].titleArray.push(obj);
            console.log('topictitle.mark', goodsList[i].titleArray)
          }

        }
      } else if(title.indexOf("|") > 0) {
        //一个子标题，标题有标志
        let miniArr = title.split('|')
        if (miniArr.length == 2) {
          if (!goodsList[i].titleArray) {
            goodsList[i].titleArray = [];
          }
          let obj = {}
          obj.title = miniArr[0];
          obj.mark = miniArr[1];
          // 英文标题
          if (obj.title.indexOf('\\') > 0) {
            let langArr = obj.title.split('\\');
            obj.title = langArr[0];
            obj.titleEnglish = langArr[1];
          } else {
            obj.titleEnglish = '';
          }
          goodsList[i].titleArray.push(obj);
          console.log('topictitle.mark', goodsList[i].titleArray)

        } 
        console.log('topictitle.mark', goodsList[i].titleArray)
      }else{
        //一个子标题，标题无标志
        if (!goodsList[i].titleArray) {
          goodsList[i].titleArray = [];
        }
        let obj = {}
        obj.title = goodsList[i].topictitle;
        obj.mark = '';
        // 英文标题
        if (obj.title.indexOf('\\') > 0) {
          let langArr = obj.title.split('\\');
          obj.title = langArr[0];
          obj.titleEnglish = langArr[1];
        } else {
          obj.titleEnglish = '';
        }
        goodsList[i].titleArray.push(obj);
        console.log('topictitle.mark', goodsList[i].titleArray)
      }
      
    }
    that.setData({
      goodsList: goodsList
    })
  },

  markGoodsListWithRec: function () {
    var that = this;
    var goodsList = that.data.goodsList;
    for (var i = 0; i < goodsList.length; i++) {
      let title = goodsList[i].topictitle;
      if (title.indexOf(":") > 0) {
        let miniArr = title.split(':')
        if (miniArr.length == 2) {
          if (!goodsList[i].RecMark) {
            goodsList[i].RecMark = [];
          }
          let obj = {}
          obj.title = miniArr[0];
          obj.mark = miniArr[1];
          goodsList[i].topictitle = miniArr[0];
          goodsList[i].RecMark.push(obj);
          console.log('topictitle.RecMark', goodsList[i].RecMark)

        }else{

        }
        console.log('topictitle.RecMark', goodsList[i].RecMark)
      } else {
        if (!goodsList[i].RecMark) {
          goodsList[i].RecMark = [];
        }
        let obj = {}
        obj.title = goodsList[i].topictitle;
        obj.mark = '';

        goodsList[i].RecMark.push(obj);
        console.log('topictitle.RecMark', goodsList[i].RecMark)
      }

    }
    that.setData({
      goodsList: goodsList
    })
  },

  markAttrGroups: function () {
    var that = this;
    var Groups = that.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      //英文属性名
      if (Groups[i].groupName.indexOf('\\') > 0) {
        let gnameArr = Groups[i].groupName.split('\\');
        Groups[i].groupName = gnameArr[0];
        Groups[i].groupNameEng = gnameArr[1];
      } else {
        Groups[i].groupNameEng = '';
      }
      for (var j = 0; j < Groups[i].subList.length; j++){
        let title = Groups[i].subList[j].attributeName
        if (title.indexOf("|") > 0) {
          let Arr = title.split('|')
          Groups[i].subList[j].attributeName = Arr[0]
          Groups[i].subList[j].mark = Arr[1];
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
          console.log('markAttrGroups', Groups[i].subList[j].mark)
          console.log('markAttrGroups---attributeNameEng', Groups[i].subList[j].attributeNameEng)
        }else{
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
        }
      }
      

    }
    that.setData({
      attributeGroups: Groups
    })

    console.log('AttrGroups', Groups)
  },

  //检查2级分类是否存在;赋值给childArr
  checkChildArray: function (e) {
    var that = this;
    var Groups = that.data.attributeGroupsOriginal;
    if (e.currentTarget.dataset.groupid.length == 3) {
      that.setData({
        childArr: [],
        existChildArr: false
      })

    }
    for (var i = 0; i < Groups.length; i++) {
      if (Groups[i].groupId == e.currentTarget.dataset.groupid && Groups[i].attributeId == e.currentTarget.dataset.value && Groups[i].erji) {
        var childArr = Groups[i].erji;
        for (var j = 0; j < childArr.length;j++) {
          childArr[j].checked==false;
          //英文属性名
          if (childArr[j].attributeName.indexOf('\\') > 0) {
            let nameArr = childArr[j].attributeName.split('\\');
            childArr[j].attributeName = nameArr[0];
            childArr[j].attributeNameEng = nameArr[1];
          } else {
            childArr[j].attributeNameEng = '';
          }
        }
        that.setData({
          childArr: childArr,
          existChildArr:true
        })
        
        console.log('childArr', childArr)
      }
    }

    //更新check状态
    var childArr = that.data.childArr;
    for (var k = 0; k < childArr.length; k++) {
      if (childArr[k].groupId == e.currentTarget.dataset.groupid && childArr[k].attributeId == e.currentTarget.dataset.value) {
        childArr[k].checked = true;
      } else {
        childArr[k].checked = false;
      }
    }
    that.setData({
      childArr: childArr,
      showSubDrink: that.data.existChildArr ? true : false
      
    })
    that.pageScrollToBottom();
    if (!that.data.showSubDrink && that.data.existChildArr) {
      that.showSubDrink()

    }
    
  },

  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    if (util.orgid == 12545) {
      animation.translateY(300).step()
    } else {    

      animation.translate(0, 300).scale3d(0, 0, 0).step()
    }
    this.setData({
      animationData: animation.export(),
      showAttribute: util.orgid == 12545 ? true : false,
      // showMoreAct: util.orgid == 17784 || util.orgid == 18681 ? true : false,
      showSendTime: util.orgid == 18681 || util.orgid == 12809 || util.orgid == 21780 ? true : false,
      showAttribute: util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484
 ? true : false,
    })
    setTimeout(function () {
      if (util.orgid == 12545) {
        animation.translateY(0).step()
      } else {
        animation.scale3d(1, 1, 1).step()
        animation.translate(0, 0).step()

      }
      this.setData({
        animationData: animation.export(),
        showAttribute: util.orgid == 12545 ? true : false,
        showSendTime: util.orgid == 18681 || util.orgid == 12809 || util.orgid == 21780 ? true : false,
        showAttribute: util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484 ? true : false,
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    var animationbar = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.animationbar = animationbar
    if (util.orgid == 12545) {
      animation.translateY(300).step()
    } else {
      animation.translate(0, 300).scale3d(0, 0, 0).step()
      animationbar.scale3d(2, 2, 2).step()

    }
    this.setData({
      animationData: animation.export(),
      animationDatabar: animationbar.export(),
    })
    setTimeout(function () {
      animationbar.scale3d(1, 1, 1).step()
      this.setData({
        animationData: animation.export(),
        animationDatabar: animationbar.export(),
        showAttribute:  false,
        showMoreAct: false,
        showSendTime:false
      })
    }.bind(this), 200)
  },
  showModalAct: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showMoreAct: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showMoreAct: true
      })
    }.bind(this), 200)
  },
  showModalSub: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDatasub: animation.export(),
      showSubDrink: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDatasub: animation.export(),
        showSubDrink: true
      })
    }.bind(this), 200)
  },

  hideModalSub: function () {
    var that=this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDatasub: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDatasub: animation.export(),
        showSubDrink:  false
      })
      that.pageScrollToBottom();
    }.bind(this), 200);
  },
  hideModalAct: function () {
    var that=this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showMoreAct:  false
      })
      // that.pageScrollToBottom();
    }.bind(this), 200);
  },
  pageScrollToBottom: function () {
    var that=this;
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom
      });
      that.setData({
        scrollTop: rect.bottom
      })
      console.log("pageScrollToBottom", rect.bottom)
    }).exec()
  },

  //门店优惠活动
  showMoreActivity: function () {
    this.showModalAct();
  },
  showSubDrink: function () {
    this.showModalSub();
  },
  changeTabCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) { return false; }
    else {
      this.setData({
        tabcurrcata: cur
      })
    }
  },
  changeCommentCata: function (e) {
    console.log("Commentcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.commentcurrcata == cur) { return false; }
    else {
      this.setData({
        commentcurrcata: cur
      })
    }
  },


  compare: function (property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value2 - value1;
    }
  },

  // 获取AddDayCount天后的日期
  getDateStr:function(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期 
    var d = dd.getDate();
    return y + "-" + util.formatNumber(m) + "-" + util.formatNumber(d);
  },
  // 初始化日期时间选择器
  datetimePickerInit:function(){
    var multiArray=[]
    var dateList=[]
    var timeList=[]
    for(var i=0;i<7;i++){
      dateList[i] = this.getDateStr(i);
    }
    multiArray.push(dateList);
    timeList=this.getTimeList();
    multiArray.push(timeList);
    var multiIndex=[0,0]
    this.setData({
      multiArray: multiArray,
      multiIndex: multiIndex
    });
    console.log("multiArray", multiArray)
    console.log('booktime时间选择器初始化', wx.getStorageSync("booktime") || '');
  } ,
  // 现在就买
  sendImediatly: function (){
    this.hideModal();
    wx.removeStorageSync('booktime');
    console.log('sendImediatly', wx.getStorageSync("booktime"));
    this.setData({
      sendImediatly:true,
      timenow: util.formatNumber(new Date().getHours()) + ":" + util.formatNumber(new Date().getMinutes())
    })
  },

  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    var  multiArray=this.data.multiArray;
    var  multiIndex=this.data.multiIndex;
    wx.setStorageSync("booktime", multiArray[0][multiIndex[0]]+" "+multiArray[1][multiIndex[1]]);
    console.log('booktime', wx.getStorageSync("booktime") || '');
    this.setData({
      sendImediatly: false
    })
    this.hideModal();
  },

  bindMultiPickerColumnChange: function (e) {
    var that=this
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    var timeList = []
    if (e.detail.column == 0 && e.detail.value == 0) {    

      data.multiArray[1] = this.getTimeList();
      data.multiIndex[1]=0;
      console.log('timeList', this.getTimeList());
      
    } else if (e.detail.column == 0){
      for (var i = 0; i < 24; i++) {
        for (var j = 0; j < 4; j++) {
          let minutes = j * 15 == 0 ? "00" : j * 15
          timeList.push(util.formatNumber(i) + ":" + minutes);
        }
      }
      timeList.forEach(function (m, i) {
        let n = that.data.multiArray[1][that.data.multiIndex[1]]
        console.log("nnn", n)
        if (m == n) {
          data.multiIndex[1] = i;
        }

      })
      data.multiArray[1] = timeList;
      
      // data.multiIndex[1] = 0;  
    }
    this.setData(data);
  },
  showSendTimePicker: function () {
    // this.setData({
    //   showSendTime:true
    // })
    this.showModal();
  },
  // 当前小时段分钟列表
  getTimeList:function(){
    var dd = new Date();
    var timeList = []
    for (var i = dd.getHours(); i < 24; i++) {
      if (i == dd.getHours()) {
        for (var j = parseInt(dd.getMinutes() / 15) + 1; j < 4; j++) {
          let minutes = j * 15 == 0 ? "00" : j * 15
          timeList.push(util.formatNumber(i) + ":" + minutes);

        }

      } else {
        for (var j = 0; j < 4; j++) {

          let minutes = j * 15 == 0 ? "00" : j * 15
          timeList.push(i + ":" + minutes);
        }

      }
    }
    return timeList
  },

  postUserScore: function (e) {

    console.log("e: ", e);
    var that = this;
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var ac = 'postuserscore';
    var privatekey = utilMd5.hexMD5(uid + ac + token);//私钥
    var params = {
      ac: ac,
      privatekey: privatekey,
      postuid: that.data.ghsid,
      uid: uid,
      score: parseInt(e.detail.value) + 1,
      subject: e.currentTarget.dataset.subject
    }
    var toastStr = "点评成功！";
    console.log("postuserscore params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        console.log("点评", responseData.data);
        var result = responseData.data;
        if (result.res) {
          app.dialogToast(toastStr, 'success');
          that.getghs();
          console.log(toastStr, result);
        }
      }
    });
  },

  getghs: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghswithscore",
      orgid: util.orgid,
      page: 1,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        // if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484 || util.orgid == 12809 || util.orgid == 21780) {
        //   that.setData({
        //     ghs: result[0]
        //   })
        // }
        for (var i = 0; i < result.length; i++) {
          
          if (result[i].gcataid == that.data.ghs.gcataid) {
            var uid = result[i].uid;
            var title = result[i].username;
            if (result[i].subjectlist.length < 2) {
              var existservice = false;
              var existquality = false;

              result[i].subjectlist.forEach(function (m, j) {
                existservice = m.subject == 'service' ? true : false
                existquality = m.subject == 'quality' ? true : false
              })
              if (!existservice) {
                result[i].subjectlist.push({ subject: 'service', score: 0 })
              }
              if (!existquality) {
                result[i].subjectlist.push({ subject: 'quality', score: 0 })
              }

              console.log("result[i].subjectlist", result[i].subjectlist)
            }
            if (!result[i].topic){
              result[i].topic={}
              result[i].topic.message=''
            }
            console.log("result[i].topic.message", result[i].topic.message)
            
            console.log("好评====", result[i])
            that.setData({
              ghsList: result,  
              ghs: result[i],
              ghsid: result[i].uid,
              ghsname: result[i].username,
              ghsgoodrate: (result[i].goodrate * 100).toFixed(0),//好评比率%
              ghsscore: result[i].scorenum == 0 ? 0.0 : (result[i].scorecoin / result[i].scorenum).toFixed(1),
              // ghsimgurls: WxParse.getImgurls('detailMessage', 'html', result[i].topic.message, that, 12).imageUrls
              // markers: [{
              //   id: 1,
              //   latitude: result[i].lat,
              //   longitude: result[i].lon,
              //   name: result[i].address
              // }],
            });

            console.log("that.data.ghsscore===", that.data.ghsscore);
            console.log("ghs", that.data.ghs);
            if (result[i].topicid){
              console.log("result[i].topicid", result[i].topicid)              
              that.loadghsCommentList(result[i].topicid, 1);
            }
            that.loadDiscountList(result[i].uid,1);

          }
        }
      }
    });
  },


  inputFinish: function (e) {
    var comment = e.detail.value;
    console.log("输入信息：" + comment);
    this.setData({
      commentValue: comment
    })
  },
  showCommentView: function (e) {
    this.setData({
      hide_commentview: false,
      // data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function () {
    this.setData({
      hide_commentview: true
    })
  },
  addComment: function (e) {
    // if (wxAuthFail) {
    //   app.reAuthorize(this.reGetUserInfo);
    //   return;
    // }

    var that = this;
    var uid = e.currentTarget.dataset.uid ? e.currentTarget.dataset.uid : that.data.uid;
    var token = e.currentTarget.dataset.token ? e.currentTarget.dataset.token : that.data.token;
    var catatype = e.currentTarget.dataset.catatype;
    var replyid = e.currentTarget.dataset.replyid;
    var message = e.currentTarget.dataset.message ? e.currentTarget.dataset.message : that.data.commentValue;
    if (!message) {
      app.dialog(that.data.tc == 1 ? '請輸入內容' : '请输入内容', 'loading');
      return;
    }
    var privatekey = utilMd5.hexMD5(uid + 'topiccomment' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccomment",
        uid: uid,
        id: that.data.ghs.topicid,
        type: catatype,
        replyid: replyid,
        message: message,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("topiccomment==data==");
        var txt = replyid > 0 ? (that.data.tc == 1 ? '回復' : '回复') : (that.data.tc == 1 ? '評論' : '评论');
        if (data.msg === "true") {
          that.setData({
            isLiked: true
          });
          that.setData({
            commentMsg: ''
          })

          app.dialog(txt + that.data.tc == 1 ? '成功' : '成功', 'success', that.getghs());
        } else {
          app.dialog(txt + that.data.tc == 1 ? '失敗' : '失败', 'loading');
        }
      }
    });
  },

  //读取所有评论
  loadghsCommentList: function (gid, page) {
    console.log("loadghsCommentList====gid", gid);
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccommentlist",
        id: gid,
        page: page,
        num: 10
      },

      success: function (responseData) {
        var data = responseData.data;
        console.log("ghs评论：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.date = util.formatTime(new Date(parseInt(m.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },



  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },
  loadCatadataCounts:function(){
    var that=this;
    var gwc_count=0;
    that.data.catadata.forEach(function(m,i){
      m.counts = 0
      that.data.allGoodsDataArray.forEach(function (n, j) {
        if(m.goods_id==n.goods_id){
          if (n.goodsList){
            n.goodsList.forEach(function (l, k) {
              if (l.selectednum) {
                if (!m.counts) {
                  m.counts = 0
                }
                m.counts += l.selectednum;
                gwc_count += l.selectednum;
                console.log("m.counts+++")
              }
            })
          }
          
        }
      })
    })
    console.log("catadata==3==",that.data.catadata);
    that.setData({
      catadata:that.data.catadata
    })

    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    if (util.orgid == 18681 || util.orgid == 12809 || util.orgid == 21780) {
      var gwc_count = 0;
      gwc_datas.forEach(function (m, i) {
        gwc_count += m.buycount
      })
      this.setData({
        gwc_count_aoka: gwc_count,
      });

    }
  },
  //读取所有优惠信息
  loadDiscountList: function (ghsid, page) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "discountlist",
        id: ghsid,
        page: page,
        num: 10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("优惠列表：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.date = util.formatTime(new Date(parseInt(m.dateline) * 1000), '-', ':');
          });
          that.setData({
            actArr: data
          });
        }
      }
    });
  },
  updateSwiperHeight:function(){
    var that=this;
    if (util.orgid == 18681 || util.orgid == 17784 || util.orgid == 12809 || util.orgid == 21780) {
      var minheight = that.data.windowHeight - that.data.windowHeight * 0.35 - 50;
      var heightnow = that.data.goodsList.length * 135
      that.setData({
        swiper_h: heightnow > minheight ? heightnow : minheight
      })

      console.log("swiper_h", that.data.swiper_h)
    }
    if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484 || util.orgid == 12809 || util.orgid == 21780) {
      var minheight = that.data.windowHeight - 110;
      var heightnow = that.data.goodsList.length * 135
      that.setData({
        swiper_h: heightnow > minheight ? heightnow : minheight
      })
      console.log("swiper_h", that.data.swiper_h)
    }
  },
  //载入所有商品家家烘焙
  getAllGoodsData:function(){
    console.log("getAllGoodsData")
    var that=this;
    var arr=that.data.allGoodsDataArray;
    for (var i = 0; i < arr.length; i++) {
      that.loadFenleiGoodsData(arr[i], i);
      that.loadFenleiTopicData(arr[i], i);
    }
  },
  loadFenleiGoodsData: function (goodsTypeOb, index) {
    console.log("loadFenleiGoodsData")
    var that = this;
    var goodsId = goodsTypeOb.goods_id;
    var params = {
      publickey: util.publiccode,
      ac: util.orgid == 18681 || util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484 
 ? "topiclistwithguige" : "topiclist",
      topictype: '4',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {

        } else {
          result.forEach(function (n, j) {
            n.message = app.parseHTMLText(n.message);
            var nodes = WxParse.getImgurls('detailMessage', 'html', n.message, that, 12).nodes;
            console.log("nodes:", nodes)

            that.whileNodes(nodes);
            console.log(messagetmp)
            n.message = messagetmp;
            messagetmp = ''
          })
          that.data.allGoodsDataArray.forEach(function (m, i) {
            if (m.goods_id == goodsId) {
              result = that.getGwcData(result)
              m.goodsList = result;

              that.loadCatadataCounts();

            }
          });
        }
        that.setData({
          allGoodsDataArray: that.data.allGoodsDataArray
        })
        console.log("allGoodsDataArray商品数据", that.data.allGoodsDataArray);
        wx.hideLoading();
      }
    });
  }, 
  loadFenleiTopicData: function (goodsTypeOb, index) {
    console.log("loadFenleiTopicData")
    var that = this;
    var goodsId = goodsTypeOb.goods_id;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '8',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("Topic参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("Topic数据" + goodsId + ": ", result);
        if (result.msg) {

        } else {
          result.forEach(function (n, j) {
            n.message = app.parseHTMLText(n.message);
            var nodes = WxParse.getImgurls('detailMessage', 'html', n.message, that, 12).nodes;
            console.log("nodes:", nodes)

            that.whileNodes(nodes);
            console.log(messagetmp)
            n.message = messagetmp;
            messagetmp = ''
          })

          that.data.allGoodsDataArray.forEach(function (m, i) {
            if (m.goods_id == goodsId) {
              m.topicList = result;
            }
          });        
        }
        that.setData({
          allGoodsDataArray: that.data.allGoodsDataArray
        })
        console.log("allGoodsDataArray商品数据", that.data.allGoodsDataArray);
        wx.hideLoading();
      }
    });
  }, 
  // 购物车商品选择数数据
  getGwcData:function(data){
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    gwc_datas.forEach(function (m, i) {
      for (var j = 0; j < data.length; j++) {
        var n = data[j];
        if (0 && n.guigelist) {
          for (var k = 0; k < n.guigelist.length; k++) {
            if (m.selGuige.id == n.guigelist[k].id) {
              n.guigelist[k].selectednum = m.buycount;
            }

          }

        } else {
          if (m.id == n.id) {
            n.selectednum = m.buycount;

          }
        }
      }
    })
    return data
  },
  // 滚动列表反应
  scrollAction: function (e) {
    console.log(e)
    console.log("e.detail.source", e.detail.source)

    var that = this;
    var interval = e.timeStamp - that.data.timeStamp;
    interval = Math.abs(interval);
    if (interval < 500) {
      return
    }
    var arr = that.data.allGoodsDataArray;
    var itemBottom = 0;
    var itemTop = 0;
    for (var i = 0; i < arr.length; i++) {
      if (!arr[i].goodsList) {
        arr[i].goodsList = []
      }
      itemTop = itemBottom;
      if(i==0){
        itemBottom = itemBottom+270
      }
      itemBottom = itemBottom + 135 * arr[i].goodsList.length + 25;
      if (e.detail.scrollTop < itemBottom && e.detail.scrollTop > itemTop && that.data.currcata != i) {

        that.setData({
          currcata: i,
          goodsList: arr[i].goodsList,
          timeStamp: e.timeStamp
        })

        return
      }
    }
    // that.setData({
    //   allGoodsDataArray:arr
    // })

  },
  showGwc:function(){
    var that=this
    var gwc_datas = wx.getStorageSync('gwc_datas');
    console.log("gwc_datas", gwc_datas)
    that.setData({
      showGwc: that.data.showGwc==true?false:true,
      gouwucheData: gwc_datas,
    })

  },
  //下拉选项改变值
  bindGhsPickerChange: function (e) {//选项改变触发事件
    var that = this;
    this.setData({
      ghsIndex: e.detail.value
    })
    that.loadGoodsType();
  },


  whileNodes: function (n) {
    var that = this
    for (let i = 0; i < n.length; i++) {
      if (n[i].node && n[i].node == "text") {
        console.log("text:", n[i].text)
        messagetmp += n[i].text
        return;
      }
      if (n[i].nodes) {
        console.log("whileNodes:", n[i].nodes)
        that.whileNodes(n[i].nodes);
      }
    }

  },

  popupGuige:function(e){
    console.log("selectGuige")
    console.log(e.currentTarget.dataset.good)
    var that = this;
    var good = e.currentTarget.dataset.good;
    that.setData({
      good: good
    })
    that.showModal()
    that.getAttribute(e);
  },
  guigeSelect: function (e) {
    var that = this;
    var selGuige = e.currentTarget.dataset.guige;
    var index = e.currentTarget.dataset.idx;
    var good = that.data.good;
    good.selGuige = selGuige;
    good.guigelist[index].checked = true;
    var list = good.guigelist;
    for (var i = 0; i < list.length;i++){
      if (i != index) {
        list[i].checked = false
      }
    }
    good.guigelist = list;
    this.setData({
      good: good
    })
  },
  selectAttr: function (e) {
    var that = this;
    var gi = e.currentTarget.dataset.groupindex;
    var ai = e.currentTarget.dataset.attrindex;
    var good = that.data.good;
    var groups = good.attributeGroups;
    console.log(e.currentTarget.dataset)
    groups[gi].subList[ai].checked = true;

    console.log("groups[gi].subList[ai]", groups[gi].subList[ai])
    console.log("subList[ai]", groups[gi].subList[ai])
    console.log("groups[gi]", groups[gi])
    var list = groups[gi].subList;
    for (var i = 0; i < list.length;i++){
      if (i != ai) {
        list[i].checked = false
      }
    }
    if (!good.attribute){
      good.attribute=[];
    }
    
    for (var i = 0; i < good.attribute.length; i++) {
      if (good.attribute[i].groupId == groups[gi].groupId){
        good.attribute.splice(i, 1); // 去除旧属性项       
      }
      console.log("del")
    }
    
    let itemOb = {};
    itemOb.groupId = groups[gi].groupId;
    itemOb.groupName = groups[gi].groupName;
    itemOb.groupNameEng = groups[gi].groupNameEng;
    itemOb.attributeId = list[ai].attributeId;
    itemOb.attributeName = list[ai].attributeName;
    itemOb.attributeNameEng = list[ai].attributeNameEng;
    console.log("itemOb",itemOb)
    good.attribute.push(itemOb);// 添加新属性

    console.log("good.attribute", good.attribute)
    
    groups[gi].subList = list;
    good.attributeGroups = groups;
    this.setData({
      good: good
    })
  },
  getGongGaoTopic:function(){
    var that = this; //1315964
    var id=0;
    if(util.orgid==18681){
      id=1315964
    } if (util.orgid == 12809) {
      id = 1315964
    } if (util.orgid == 21780) {
      id = 1315964
    }
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topicdetail",
        topicid: id,
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("gonggao：", data);
        
          
        that.setData({
          gongGao: data
        });
      }
    });
  },
  loadGoodsType:function(){
    var that=this;
    var ghsList=that.data.ghsList;
    
    util.api({
      data: {
        "tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function (responseData) {
        console.log("goodstype", responseData.data);
        var goodsType = responseData.data;
        var goodId = this.data.goodTypeId;

        console.log("goodId", goodId);
        that.setData({
          gcataid: goodId,
        });
        if (goodId == "0") {
          if (!goodsType.msg) {
            dataall = goodsType;
            console.log("catadata==4==",dataall);
            that.setData({
              catadata: dataall,
              allGoodsDataArray: dataall,
              selectCata: dataall[0],
              gcataid: dataall[0]['goods_id'],
              nowcata: dataall[0].child
            });

            if (util.orgid == 21145 || util.orgid == 21398 || util.orgid == 21484) {
              that.getAllGoodsData();

            } else {
              that.loadGoodsListData(1);
            }
          } else {
            wx.hideLoading();
          }
        } else {
          var cata = [];
          if (!goodsType.msg) {
            for (var i = 0; i < goodsType.length; i++) {
              var gid = goodsType[i].goods_id;
              console.log("===gid===!:" + gid);
              if (goodId == gid) {
                cata = goodsType[i].child == undefined ? goodsType : goodsType[i].child;
                break;
              }

            }
            console.log("===cata===!:", cata);
            if (cata && cata.length >= 1) {
              dataall = cata;
            } else {
              dataall = goodsType;
            }
            console.log("catadata==5==",dataall);
            that.setData({
              catadata: dataall,
              allGoodsDataArray: dataall,
              selectCata: dataall[0],
              nowcata: dataall
            });
            if (util.orgid == 21145 || util.orgid == 21398) {
              that.getAllGoodsData();

            } else {
              that.loadGoodsListData(1);
            }
          } else {
            wx.hideLoading();
          }
        }

      }
    });
  },

  videoErrorCallback: function (e) {
    console.log('视频错误信息:'+e.detail.errMsg);
  },
  
})